<template>
	<view class="container">
		<!-- 自定义头部组件 -->
		<myHead :title="songName"></myHead>
		<view class="player">
			<view class="pointer"></view>
			<img ref="songImg" :src="songPicUrl" class="playing">
			<text @click="togglePlayPause"
				:class="isPlaying ? 'iconfont icon-zanting' : 'iconfont icon-bofang1'"></text>
			<view class="lyric-container" ref="lyricContainer">
				<view class="lyric" v-for="(line, index) in lyricLines" :key="index"
					:class="{ 'highlighted': index === lyricIndex }"
					:style="{ transform : 'translateY(' +  - (lyricIndex - 2) * 50  + 'rpx)' }">{{ line }}</view>
			</view>
		</view>
	</view>
</template>


<script>
	import myHead from '../../components/myHead/myHead.vue'
	import {
		songDetail,
		songUrl,
		songLyric
	} from '../../commom/api.js';

	export default {
		data() {
			return {
				songId: '',
				songAudioUrl: '',
				songName: '',
				songLyric: '',
				songPicUrl: '',
				isPlaying: false,
				innerAudioContext: null,
				currentTime: 0,
				lyricIndex: 0,
			};
		},
		computed: {
			lyricLines() {
				return this.songLyric.replace(/\[[^\]]*\]/g, '').split('\n');
			}
		},
		created() {
			this.initSongUrl();
		},
		methods: {
			togglePlayPause() {
				if (this.isPlaying) {
					this.pauseMusic();
				} else {
					this.playMusic();
				}
			},
			async initSongUrl() {
				try {
					const id = this.$route.query.songId;
					this.songId = id;
					const res1 = await songUrl(id);
					this.songAudioUrl = res1.data.data[0].url;
					const res2 = await songDetail(id);
					this.songName = res2.data.songs[0].name;
					this.songPicUrl = res2.data.songs[0].al.picUrl;
					const res3 = await songLyric(id);
					this.songLyric = res3.data.lrc.lyric;
					this.playMusic();
				} catch (error) {
					console.error('获取歌曲链接失败', error);
				}
			},

			playMusic() {
				if (!this.songAudioUrl) {
					console.error('歌曲链接为空');
					return;
				}
				if (!this.innerAudioContext) {
					this.innerAudioContext = uni.createInnerAudioContext();
					this.innerAudioContext.onPlay(() => {
						console.log('开始播放:' + this.songName);
						this.isPlaying = true;
						this.$refs.songImg.classList.add('playing');
						this.lyricIndex = 0;
						this.scrollLyric();
					});
					this.innerAudioContext.onTimeUpdate(() => {
						this.currentTime = this.innerAudioContext.currentTime;
						this.updateLyricIndex();
					});
				}
				this.innerAudioContext.src = this.songAudioUrl;
				this.innerAudioContext.autoplay = true;
				this.isPlaying = true;
			},
			updateLyricIndex() {
	
				const lyricTimes = this.parseLyricTime();

				for (let i = 0; i < lyricTimes.length; i++) {

					if (this.currentTime >= lyricTimes[i] && (!lyricTimes[i + 1] || this.currentTime < lyricTimes[i +
							1])) {
					
						this.lyricIndex = i;
						break;
					}
				}
			},
			parseLyricTime() {
				const lyricLines = this.songLyric.split('\n'); // 将歌词按行分割
				const lyricTimes = [];
				for (let line of lyricLines) {
					const timeStr = line.match(/\[(\d{2}):(\d{2})\.(\d{2,3})]/); // 正则匹配时间格式 [mm:ss.ms]
					if (timeStr) {
						const minutes = parseInt(timeStr[1]); // 分钟
						const seconds = parseInt(timeStr[2]); // 秒钟
						const milliseconds = parseInt(timeStr[3].padEnd(3, '0')); // 毫秒
						const time = minutes * 60 + seconds + milliseconds / 1000; // 计算总秒数
						lyricTimes.push(time); 
					}
				}
				return lyricTimes; 
			},
			pauseMusic() {
				if (this.innerAudioContext && this.isPlaying) {
					this.innerAudioContext.pause();
					this.isPlaying = false;
					console.log('暂停播放:' + this.songName);
					this.$refs.songImg.classList.remove('playing');
				}
			},
		},
		beforeDestroy() {
			if (this.innerAudioContext) {
				this.innerAudioContext.pause();
				this.innerAudioContext.destroy();
			}
		}
	};
</script>

<style>
	.player {
		position: absolute;
		width: 530rpx;
		height: 530rpx;
		background-image: url("@/static/disc.png");
		background-size: cover;
		top: 219rpx;
		left: 50%;
		transform: translateX(-50%);
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.player img {
		position: absolute;
		z-index: -1;
		width: 175px;
		border-radius: 50%;
	}

	.pointer {
		position: absolute;
		bottom: 390rpx;
		right: 120rpx;
		width: 170rpx;
		height: 260rpx;
		background-image: url('@/static/needle.png');
		background-size: cover;
	}

	.iconfont {
		font-size: 60rpx;
		color: darkgray;
	}

	.playing {
		animation: zhuan 10s linear infinite;
	}

	@keyframes zhuan {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}

	.lyric-container {
		position: absolute;
		top: 540rpx;
		width: 100%;
		height: 260rpx;
		overflow: auto;
	}

	.lyric {
		line-height: 50rpx;
		text-align: center;
		font-size: 28rpx;
		color: #414141;
		transition: transform 0.3s ease;
		/* 添加过渡效果 */
	}

	.highlighted {
		color: pink;
	}
</style>